#include<iostream>
#include<vector>
using namespace std;

class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        int sum = 0;
        for (auto e : stones) sum += e;
        int V = sum / 2;
        int len = stones.size();
        vector<vector<int>> dp(len + 1, vector<int>(V + 1, 0));
        for (int i = 1; i <= len; i++) {
            for (int j = 1; j <= V; j++) {
                dp[i][j] = dp[i - 1][j];
                if (j >= stones[i - 1]) {
                    dp[i][j] = max(dp[i][j], dp[i - 1][j - stones[i - 1]] + stones[i - 1]);
                }
            }
        }
        return sum - 2 * dp[len][V];
    }
};


class Solution {
public:
    int lastStoneWeightII(vector<int>& stones) {
        int sum = 0;
        for (auto e : stones) sum += e;
        int V = sum / 2;
        int len = stones.size();
        vector<int> dp(V + 1, 0);
        for (int i = 1; i <= len; i++) {
            for (int j = V; j >= stones[i - 1]; j--) {
                dp[j] = max(dp[j], dp[j - stones[i - 1]] + stones[i - 1]);
            }
        }
        return sum - 2 * dp[V];
    }
};

